package com.huilink.webmail.service.impl;

import java.util.List;
import java.util.concurrent.Executor;

import org.apache.commons.mail.Email;
import org.apache.commons.mail.SimpleEmail;

import com.huilink.db.WebMailDAO;
import com.huilink.db.dbo.AdminMailSettingDbo;
import com.huilink.webmail.dtolayer.AdminMailSetting;
import com.huilink.webmail.service.api.MailSender;
import com.huilink.webmail.service.api.WebMailService;
import com.huilink.webmail.service.api.WebMailServiceListener;

public class WebMailServiceImpl implements WebMailService {
	
	private WebMailDAO webMailDao;
	
	//should be a list here 
	private WebMailServiceListener l;
	
	private Email emailService;
	
	
	private Executor mailSenderExecutor;
	
	private AdminMailSettingDbo adminMailSetting;
	
	
	//I hate this
	public WebMailServiceImpl(WebMailDAO webMailDao,Executor executor) {
		this.webMailDao = webMailDao;
		this.mailSenderExecutor = executor;
	}

	
	public void addWebMailServiceListener(WebMailServiceListener l) {
		this.l = l;

	}

	public void removeWebMailServiceListener(WebMailServiceListener l) {
		this.l = null;

	}

	public void setDB(WebMailDAO webMailDao) {
		this.webMailDao = webMailDao;

	}

	public void setEmailService(Email mail) {
		this.emailService = mail;

	}

	//just for the test
	public void setExecutor(Executor executor) {
		this.mailSenderExecutor = executor;

	}

	public void start() {
		// TODO Auto-generated method stub

	}

	public void stop() {
		// TODO Auto-generated method stub

	}

	public AdminMailSetting getAdminMailSetting() {
		adminMailSetting = webMailDao.getAdminMailSetting();
		return Translator.translateAdminMailSetting(adminMailSetting);
	}

	/**
	 * @deprecated
	 */
	public List<AdminMailSetting> getAdminMailSettings() {
		// TODO Auto-generated method stub
		return null;
	}

	public AdminMailSetting saveAdminMailSetting(AdminMailSetting adminSetting) {
		AdminMailSettingDbo settingDbo = Translator.translateAdminMailSetting(adminSetting);
		if(settingDbo==null)
			throw new IllegalArgumentException("Admin mail setting is null");
		adminMailSetting = webMailDao.saveOrUpdateAdminMailSetting(settingDbo);
		return Translator.translateAdminMailSetting(adminMailSetting);
	}


	public MailSender createMailSender() {
		if(adminMailSetting==null){
			adminMailSetting = webMailDao.getAdminMailSetting();
		}
		if(adminMailSetting==null)
			throw new IllegalStateException("Need set admin mail-box information first");
		if(emailService==null)
			emailService = new SimpleEmail();
		return new MailSenderImpl(mailSenderExecutor,emailService,adminMailSetting);
	}



}
